using Aliyun.OSS;

namespace IMServer.Services;

public class OssService
{
    private readonly string _endpoint = "***";
    private readonly string _accessKeyId = "***";
    private readonly string _accessKeySecret = "***";
    private readonly string _bucketName = "***";
    
    private static OssService? _instance;
    public static OssService Instance => _instance ??= new OssService();
    
    private OssService() { }

    public async Task<string> UploadFileAsync(IFormFile file)
    {
        try
        {
            var ossClient = new OssClient(_endpoint, _accessKeyId, _accessKeySecret);

            using var stream = file.OpenReadStream();
            // 生成文件名：avatars/年月日/GUID.扩展名
            var fileName = $"avatars/{DateTime.Now:yyyyMMdd}/{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";

            _ = await Task.Run(() => ossClient.PutObject(_bucketName, fileName, stream));

            return $"https://{_bucketName}.{_endpoint}/{fileName}";
        }
        catch (Exception ex)
        {
            throw new Exception($"Failed to upload file to OSS: {ex.Message}");
        }
    }
} 